<template>
  <div id="AdviceContent" class="mainContent">
    <div class="clearfix boxOuter">
      <div class="checkBox clearfix pull-left" v-clickoutside="handleClose">
        <div class="select">
          <p :class="{'up' : showEn}" @click="showEnj" style="text-align:right">{{enjoin}}</p>
          <ul :class="['list-link',{'show': showEn}]">
            <li
              v-for="(item,index) in tab"
              :key="item.value"
              @click="changeEn($event)"
            >{{item.label}}</li>
          </ul>
        </div>
        <div class="select">
          <p :class="{'up' : showTy }" @click="showType" style="text-align:right">{{types}}</p>
          <ul :class="['list-link',{'show': showTy}]">
            <li
              v-for="(item,index) in tabType"
              :key="item.value"
              @click="changeTy($event)"
            >{{item.label}}</li>
          </ul>
        </div>
        <div class="select channelDiv">
          <p :class="{'up' : showApp }" @click="showAppro" style="text-align:right">{{approach}}</p>
          <ul :class="['list-link','channel',{'show': showApp}]">
            <li
              v-for="(item,index) in tabApproach"
              :key="item.value"
              @click="changeApp($event)"
            >{{item.ADMINISTRATION}}</li>
          </ul>
        </div>
        <div class="select">
          <p :class="{'up' : showSta}" @click="showStatus" style="text-align:right">{{status}}</p>
          <ul :class="['list-link',{'show': showSta}]">
            <li
              v-for="(item,index) in  tabStatus"
              :key="item.value"
              @click="changeSta($event)"
            >{{item.label}}</li>
          </ul>
        </div>
      </div>
      <div class="box">
        <vue-datepicker-local
          class="pull-left databox"
          v-model="emptyTime"
          clearable
          
        />
        <div class="btn-search left">
          <input
            type="text"
            name="search"
            placeholder="请输入名称"
            v-model="searchVal"
            @change="searchValue"
            style="    height: 32px; width: calc(95% - 18px); border: none;"
          />
          <img
            src="../../../../static/images/search.png"
            height="18"
            width="18"
            alt
            @click="btnSearch"
          />
        </div>
      </div>

    </div>
    <template v-if="count">
      <div class="countThead">
        <table class="table" :style="{'width':width}">
          <thead>
            <tr>
              <th class="text-center" width="12%">开立时间</th>
              <th class="text-center" width="31%">医嘱内容</th>
              <th class="text-center" width="12%">剂量</th>
              <th class="text-center" width="8%">频次</th>
              <th class="text-center" width="7%">长/临</th>
              <th class="text-center" width="14%">途径</th>
              <th class="text-center" width="9%">类型</th>
              <th class="text-center" width="7%">状态</th>
            </tr>
          </thead>
        </table>
      </div>
      <div class="countTbody" v-if="patientList.length" @scroll="onScroll">
        <table class="table table-striped">
          <tbody>
            <tr
              v-for="(item,index) in patientList"
              :key="index"
              :data-id="item.ORDER_NO"
              @click="isModal($event)"
            >
              <td
                class="text-center timeStart"
                width="12%"
                :rowspan="item.ORDER_NOspan"
                :class="{hidden: item.ORDER_NOdis}"
              >{{item.ENTER_TIME | filterDateTime}}</td>
              <td v-html="msg(item.ORDER_TEXT)" class="limitHeight" width="31%"></td>
              <td class="text-center" width="12%">{{item.DOSAGE | numFilter(item.ORDER_UNIT)}}</td>
              <td class="text-center" width="8%">{{item.FREQUENCY}}</td>
              <td class="text-center" width="7%">{{item.Type}}</td>
              <td class="text-center" width="14%">{{item.ADMINISTRATION}}</td>
              <td class="text-center" width="9%">{{item.ValidFlag}}</td>
              <td class="text-center" width="7%">{{item.ExecutingState}}</td>
            </tr>
          </tbody>
        </table>
        <Loading v-if="showScroll"></Loading>
        <modal v-show="showDialog" :dialog-option="dialogOption" ref="dialog"></modal>
        <Loading v-if="JSON.stringify(dialogOption.Data) == '{}'&& isModalB "></Loading>
      </div>
    </template>
    <Loading v-if="isShow &&patientList.length== 0"></Loading>
    <noSearch v-if="!isShow && patientList.length == 0"></noSearch>
  </div>
</template>
<script>
import {
  apiMedicalOrderApproachList,
  apiMedicalOrderList,
  apiOneMedicalOrder
} from "@/api/api"; // 导入我们的医嘱获取途径下拉选择api接口 和 医嘱列表api接口 和 医嘱详情接口
import Loading from "@/components/loading/loading"; //导入loading组件
import VueDatepickerLocal from "@/components/datepicker/VueDatepickerLocal";
import Modal from "@/views/medicalAdvice/medicalAdviceContent/medicalAdviceDetails"; //导入医嘱详情模态框
import noSearch from "@/components/search/noSearch"; //导入没有搜索结果组件
import Bus from "@/components/common/bus"; //引入公共媒介JS BUS
export default {
  data: function() {
    return {
      tab: [
        { label: "全部", value: 1 },
        { label: "长嘱", value: 2 },
        { label: "临嘱", value: 3 }
      ],
      tabType: [
        { label: "全部", value: 1 },
        { label: "药嘱", value: 2 },
        { label: "非药嘱", value: 3 }
      ],
      tabApproach: [],
      tabStatus: [
        { label: "全部", value: 1 },
        { label: "新开", value: 2 },
        { label: "校验", value: 3 },
        { label: "执行", value: 4 },
        { label: "作废", value: 5 },
        { label: "停止", value: 6 }
      ],
      isShow: true,
      showEn: false,
      showTy: false,
      showApp: false,
      showSta: false,
      enjoin: "长/临",
      types: "类型",
      approach: "途径",
      status: "状态",
      patientList: [],
      pageSize: 20, //每页显示20条数据
      currentPage: 1, //当前页码
      count: 0, //总页数
      ID_Order: "", //当前点击的医嘱列表ID（医嘱号）
      showDialog: false, //标识模态框是否出现
      dialogOption: {
        title: "医嘱详情",
        Data: {}
      },
      width: "100%",
      isModalB: false,
      emptyTime: "",
      dataTime: "0000-00-00",
      //懒加载
      isScroll: true,
      showScroll: false,
      searchVal: ""
    };
  },
  watch: {
    dataTime: {
      handler(curVal, oldVal) {
        if (this.dataTime == "") {
          this.dataTime = "0000-00-00";
          this.isShow = true;
          this.patientList = [];
          this.getMedicalOrderList();
        } else if (this.dataTime == "NaN-NaN-NaN") {
          this.dataTime = "0000-00-00";
          this.isShow = true;
          this.patientList = [];
          this.getMedicalOrderList();
        } else {
          this.isShow = true;
          this.patientList = [];
          this.getMedicalOrderList();
        }
      }
    }
  },
  created() {
    this.getIsPadPc();
    //请求途径数据
    this.getMedicalOrderApproachList();
  },
  mounted() {
    //window.addEventListener('scroll', this.onScroll)
    //请求第一页数据
    this.getMedicalOrderList();
    Bus.$on("timePicker", e => {
      this.patientList = [];
      this.dataTime = e.trim();
    });
  },
  methods: {
    showEnj() {
      this.showEn = !this.showEn;
      this.showTy = false;
      this.showApp = false;
      this.showSta = false;
    },
    showType() {
      this.showTy = !this.showTy;
      this.showEn = false;
      this.showApp = false;
      this.showSta = false;
    },
    showAppro() {
      this.showApp = !this.showApp;
      this.showEn = false;
      this.showTy = false;
      this.showSta = false;
    },
    showStatus() {
      this.showSta = !this.showSta;
      this.showEn = false;
      this.showTy = false;
      this.showApp = false;
    },
    changeEn(event) {
      // this.ind = e
      // this.show = ! this.show
      if ($.trim(event.currentTarget.innerHTML) == "全部") {
        this.enjoin = "长/临";
      } else {
        this.enjoin = $.trim(event.currentTarget.innerHTML);
      }
      this.showEn = false;
      this.patientList = [];
      this.currentPage = 1; //初始化页码
      this.getMedicalOrderList(); //请求医嘱数据
    },
    changeTy(event) {
      if ($.trim(event.currentTarget.innerHTML) == "全部") {
        this.types = "类型";
      } else {
        this.types = $.trim(event.currentTarget.innerHTML);
      }
      this.showTy = false;
      this.patientList = [];
      this.currentPage = 1; //初始化页码
      this.getMedicalOrderList(); //请求医嘱数据
    },
    changeApp(event) {
      if ($.trim(event.currentTarget.innerHTML) == "全部") {
        this.approach = "途径";
      } else {
        this.approach = $.trim(event.currentTarget.innerHTML);
      }
      this.showApp = false;
      this.patientList = [];
      this.currentPage = 1; //初始化页码
      this.getMedicalOrderList(); //请求医嘱数据
    },
    changeSta(event) {
      if ($.trim(event.currentTarget.innerHTML) == "全部") {
        this.status = "状态";
      } else {
        this.status = $.trim(event.currentTarget.innerHTML);
      }
      this.showSta = false;
      this.patientList = [];
      this.currentPage = 1; //初始化页码
      this.getMedicalOrderList(); //请求医嘱数据
    },
    handleClose() {
      this.showApp = false;
      this.showEn = false;
      this.showTy = false;
      this.showSta = false;
    },
    btnSearch() {
      //console.log(this.searchval)
      this.isShow = true;
      this.patientList = [];
      this.getMedicalOrderList();
    },
    searchValue() {
      //当改变搜索框的值为空执行
      if (this.searchVal == "") {
        this.isShow = true;
        this.patientList = [];
        this.getMedicalOrderList();
        //console.log(this.searchVal)
      }
    },
    // 获取医嘱途径下拉内容数据
    getMedicalOrderApproachList() {
      // // 调用患者列表api接口，并且提供了参数
      apiMedicalOrderApproachList({
        patientIdIn: this.$store.getters.ID
      }).then(res => {
        if (res.Status == -1) {
          this.isShow = false;
        }
        // 把后台传入的数据赋值
        if (res.Status == 1) {
          //判断是否获取成功 为1是成功，-1为不成功
          let Json = { ADMINISTRATION: "全部" };
          let jsonarray = JSON.parse(res.Data);
          let JsonApproach = jsonarray.unshift(Json);
          this.tabApproach = jsonarray;
          this.isShow = true;
        }
      });
    },
    // 获取医嘱列表数据
    getMedicalOrderList() {
      apiMedicalOrderList({
        pageIndex: this.pageSize * this.currentPage - 19,
        pageSize: this.pageSize * this.currentPage,
        type: this.enjoin,
        medicalOrderType: this.types,
        medicalOrderState: this.status,
        patientId: this.$store.getters.ID,
        approach: this.approach,
        dateTime: this.dataTime,
        orderText: this.searchVal
      }).then(res => {
        if (JSON.parse(res).Status == -1) {
          this.isShow = false;
          this.isScroll = false;
        }
        if (JSON.parse(res).Status == 1) {
          //判断是否获取成功 为1是成功，-1为不成功
          this.isShow = true;

          if (this.currentPage == 1) {
            this.patientList = [];
          }
          let result = this.combineTime(JSON.parse(res).Data);
          this.patientList.push.apply(this.patientList, result);
          //console.log(this.patientList)
          this.isScroll = true;
          this.showScroll = false;
          this.count = Math.ceil(JSON.parse(res).TotalCount / this.pageSize); //计算总页数
        }
      });
    },
    //点击弹出详情页面
    isModal(e) {
      this.ID_Order = e.currentTarget.getAttribute("data-id");
      this.dialogOption.Data = {};
      this.isModalB = true;
      apiOneMedicalOrder({
        patientID: this.$store.getters.ID,
        MedicalOrderID: this.ID_Order
      }).then(res => {
        if (res.Status == -1) {
          this.isShow = false;
        }
        if (JSON.parse(res).Status == 1) {
          this.dialogOption.Data = JSON.parse(res).Data[0];
          //console.log(JSON.parse(res).Data[0]);
          this.showDialog = true;
          this.isShow = true;
          this.$refs.dialog
            .confirm()
            .then(() => {
              this.showDialog = false;
            })
            .catch(() => {
              this.showDialog = false;
            });
        }
      });
    },
    onScroll() {
      let viewH = $(".countTbody").height(); //可见高度
      let contentH = $(".countTbody table").height(); //内容高度
      let scrollTop = $(".countTbody").scrollTop(); //滚动高度
      if (scrollTop / (contentH - viewH) == 1 && this.isScroll) {
        //到达底部100px时,加载新内容
        if (this.currentPage >= this.count || !this.isScroll) {
          if (contentH - viewH - scrollTop <= 25) {
            this.$toast.center("已加载所有列表！");
          }
          return;
        }
        this.currentPage++;
        this.showScroll = true;
        this.isScroll = false;
        this.getMedicalOrderList();
      }
    },
    combineTime(list) {
      var k = 0;
      let field = "ORDER_NO";
      while (k < list.length) {
        list[k][field + "span"] = 1;
        list[k][field + "dis"] = false;
        for (var i = k + 1; i <= list.length - 1; i++) {
          if (list[k][field] == list[i][field] && list[k][field] != "") {
            list[k][field + "span"]++;
            list[k][field + "dis"] = false;
            list[i][field + "span"] = 1;
            list[i][field + "dis"] = true;
          } else {
            break;
          }
        }
        k = i;
      }
      return list;
    },
    getIsPadPc() {
      if (
        navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        )
      ) {
        this.width = "100%";
      } else {
        this.width = "calc(100% - 18px)";
      }
    }
  },
  filters: {
    filterDateTime(time) {
      if (!time) {
        return "";
      } else {
        return time.replace("T", " ").substring(5, 16);
      }
    },
    numFilter(str, str1) {
      if (!str) {
        return "";
      } else {
        if (Number(str).toFixed(2) == 0.0) {
          return "";
        } else {
          return Number(str).toFixed(2) + str1;
        }
      }
    }
  },
  //显示的声明组件
  components: {
    Loading,
    Modal,
    noSearch,
    VueDatepickerLocal
  }
};
</script>
<style scoped>
#AdviceContent {
  padding-bottom: 15px;
  overflow-y: auto;
  padding: 15px 0 0 0;
}

.checkBox {
  margin-left: 2.5%;
  height: 36px;
  line-height: 36px;
  width: 328px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f6f6f6;
  cursor: pointer;
  margin-bottom: 15px;
  margin-right: 30px;
}

.btn-search {
  width: 210px;
  height: 35px;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding-left: 10px;
  vertical-align: top;
}

.select {
  width: 80px;
  height: 100%;
  float: left;
}

.table > thead > tr > th {
  border-bottom: none;
}

.countThead,
.countTbody {
  width: 97%;
  margin: 0 auto;
  /*border:1px solid #f4f4f4;*/
  border-top: none;
}

.countTbody {
  border: 1px solid #ddd;
  border-top: 0;
}

.table {
  margin-bottom: 0;
}

.countThead thead tr {
  height: 42px;
  line-height: 42px;
  background-color: #11a7f3;
  color: #fff;
}

.countThead > thead > tr > th {
  border-bottom: none;
}

.countTbody {
  max-height: calc(100% - 200px);
  overflow-y: auto;
}

.countTbody tbody tr td {
  vertical-align: middle;
  border-top: 1px solid #ddd;
  color: #333;
  border-right: 1px solid #ddd;
}

.countTbody tbody tr td:last-child {
  border-right: none;
}

.countTbody tbody > tr:first-child > td {
  border-top: none;
}

.countTbody tbody tr td.limitHeight {
  vertical-align: middle;
  line-height: 20px;
  padding-left: 8px;
  color: #02bb96;
}

.select p {
  color: #000;
  position: relative;
  text-indent: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.select p:after {
  display: inline-block;
  content: "";
  width: 10px;
  height: 10px;
  background-image: url("../../../../static/images/unfold_arron.png");
  background-repeat: no-repeat;
  background-size: contain;
  vertical-align: middle;
  margin-left: 8px;
}

.select p.up:after {
  background-image: url("../../../../static/images/up_arron.png");
}

.list-link {
  position: relative;
  z-index: 9999;
  display: none;
  border: 1px solid #eee;
  left: 20px;
  width: 100px;
  background-color: #fff;
  box-shadow: 2px 5px 5px #ccc;
}

.channel {
  width: 190px;
  left: -25px;
  -webkit-column-count: 2; /* Chrome, Safari, Opera */
  -moz-column-count: 2; /* Firefox */
  column-count: 2;
}

.list-link li {
  text-align: center;
  cursor: pointer;
}

.list-link li:hover {
  background-color: #f6f6f6;
  border-bottom: 1px solid #ccc;
}
.databox {
  width: 190px; margin-right: 2.5%; border-radius: 10px;
}

.box_center{
  display: none;
}
@media screen and (max-height: 770px) {
  .countTbody {
    max-height: calc(100% - 100px);
    overflow-y: auto;
  }
}

@media screen and (max-height: 1000px) {
  .countTbody {
    max-height: calc(100% - 120px);
    overflow-y: auto;
  }
}

@media screen and (min-height: 1000px) {
  .countTbody {
    max-height: calc(100% - 300px);
    overflow-y: auto;
  }
}
@media screen and (max-width: 1024px){
  .boxOuter{
    padding: 10px 15px;
  }
  .box{
    display: flex;
    float: left;
  }
  .checkBox{
    margin-left: 0;
  }
}
@media screen and (max-width: 768px) {
  
.countThead,
.countTbody {
  min-width: 700px;
  margin: 0 auto;
  /*border:1px solid #f4f4f4;*/
  border-top: none;
}
.databox {
  /* margin-left: 2.5%; */
}
}
@media screen and (max-width: 425px) {
}
</style>
